import { Button, NavBar, Radio, Space, Toast } from "antd-mobile";
import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import $fetch from "../../../utils/app/$fetch";
import $getQuery from "../../../utils/app/$getQuery";
import $reducer from "../../../utils/app/$reducer";
import "./style.scss";

const GoodsOrderPage = () => {
  const navigate: any = useNavigate();
  const location: any = useLocation();
  const cartIds = location?.state?.cartIds;
  const $params = $getQuery();

  const initState: any = {
    resList: [],
    selectAllStatusStatus: false,
    totalCartAmount: 0,
    payType: 0,
    cartIdsParams: [],
    haveT: false,
    notes: '',
  };

  const [state, dispatch] = $reducer({ ...initState });

  useEffect(() => {
    initPage();
    handleTotalAmount();
  }, []);

  const initPage = async () => {
    if ($params?.from === "pay") {
      return;
    }
    const resList: any = await $fetch("order/generateConfirmOrder", cartIds, {
      method: "post",
      noGroupId: "no",
    });
    let cartIdsParams = [];
    const haveT = resList?.cartItemList?.find((item: any)=>item?.goodsId === 12)
    cartIdsParams = resList?.cartItemList?.map((item: any) => {
      if (item?.ticketTemType === 1) {
        // 电切券，默认为电子券
        return {
          cartId: item?.id,
          payment: 0,
        };
      } else if (item?.ticketTemType == null) {
        // 线下自提
        return {
          cartId: item?.id,
          payment: 1,
        };
      } else {
        return {
          cartId: item?.id,
          ticketTemType: item?.ticketTemType,
        };
      }
    });
    dispatch({
      haveT: haveT ? true : false,
      resList: resList?.cartItemList,
      cartIdsParams,
      totalCartAmount: resList?.totalCartAmount,
    });
  };

  // 计算总价
  const handleTotalAmount = () => {
    let totalAmount = 0;
    state?.resList?.forEach((item: any) => {
      totalAmount += item?.quantity * item?.price;
    });
    dispatch({ totalAmount });
  };

  const handlePayment = (value: any, id: any) => {
    const cartIdsParams = state?.cartIdsParams.map((cart: any) => {
      if (id === cart?.cartId) {
        cart.payment = value;
      }
      return cart;
    });
    dispatch({ cartIdsParams });
  };

  const handleSubmit = async () => {
    console.log(state?.cartIdsParams);

    const allSelected = state?.cartIdsParams.find(
      (item: any) =>
        item?.ticketTemType === 0 && item?.payment !== 0 && item?.payment !== 1
    );

    if (allSelected) {
      Toast.show("请勾选特典券的领取方式！");
      return;
    }

    if (state?.haveT && !state?.notes) {
      Toast.show("请备注T恤尺码");
      return;
    }

    try {
      const res: any = await $fetch(
        "/order/generateOrder",
        { cartIds: state?.cartIdsParams, payType: 0, notes: state?.notes },
        { loading: false, method: "post", noGroupId: "no" }
      );
      debugger;
      await $fetch("alipay/webPay", {
        outTradeNo: res?.order?.orderSn,
        subject: res?.order?.orderSn,
        totalAmount: res?.order?.orderPrice,
      });

      const outTradeNo = res?.order?.orderSn;
      const subject = res?.order?.orderSn;
      const totalAmount = res?.order?.orderPrice;

      let system = navigator.userAgent;
      let isAndroid =
        system.indexOf("Android") > -1 || system.indexOf("Adr") > -1; // android终端
      let isiOS = !!system.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      const url = `https://www.ifestive365.com:8085/alipay/webPay?outTradeNo=${outTradeNo}&subject=${subject}&totalAmount=${totalAmount}&groupId=1`
      // window.location.replace(url)
      // 使用
      if (isAndroid) {
        //android终端
        console.log("我是安卓");
        window.open(url);
      } else if (isiOS) {
        //ios终端
        console.log("我是ios");
        window.location.href = url;
      }
      
      // window.open(
      //   `https://47.101.149.72:8085/alipay/webPay?outTradeNo=${outTradeNo}&subject=${subject}&totalAmount=${totalAmount}&groupId=1`
      // );
      // setTimeout(() => {
      //   openModal(res?.order?.orderSn);
      // }, 2000);

      // navigate("/order/list");
    } catch (error) {
      navigate("/goods/list");
      console.log(error, "____error");
    }
  };

  const back = () => {
    window.history.go(-1);
  };

  return (
    <div className="container_goods_order">
      <NavBar
        style={{
          "--border-bottom": "1px #eee solid",
        }}
        onBack={back}
      >
        提交订单
      </NavBar>
      <div className="content_wraper">
        <ul className="that_goods_list">
          {state?.resList?.map((good: any) => {
            return (
              <li>
                <div className="item_good" key={good?.goodsId}>
                  <img src={good?.goodsPhoto} alt="" />
                  <div className="good_content">
                    <div>
                      <h3>{good?.goodsName}</h3>
                      <div>￥<span>{good?.price}</span></div>
                    </div>
                    <div className="num">×{good?.quantity}</div>
                  </div>
                </div>
                {/* ticketTemType 0为特典 1为电切 */}
                <div className="item_select">
                  <div>领取方式：</div>
                  {good?.ticketTemType === 0 ? (
                    <Radio.Group
                      onChange={(e: any) => handlePayment(e, good?.id)}
                    >
                      <Space direction="horizontal">
                        <Radio value={0}>电子券</Radio>
                        <Radio value={1}>线下自提</Radio>
                      </Space>
                    </Radio.Group>
                  ) : good?.ticketTemType === 1 ? (
                    <div className="center">电子券</div>
                  ) : (
                    <div className="center">线下自提</div>
                  )}
                </div>
              </li>
            );
          })}
        </ul>

        {state?.resList?.length > 0 && (
          <>
            <ul className="that_pay_type">
              <div className='remark_wraper'>
                <div>订单备注</div>
                <input placeholder="若购买T恤请备注尺码！" type="text" className='remark' onChange={(e: any)=>{
                  dispatch({notes: e.target.value})
                }}/>
              </div>
              <li>
                  <div className="alipay">支付宝支付</div>
                  <em
                    onClick={() => {
                      dispatch({ payType: 1 });
                    }}
                    className={`common_rem ${state?.payType === 1 ? "isChecked" : ""}`}
                  />
                </li>
              <li>
                <div className="weixin">微信支付</div>
                <em
                  onClick={() => {
                    dispatch({ payType: 0 });
                  }}
                  className={`common_rem ${state?.payType === 0 ? "isChecked" : ""}`}
                />
              </li>
            </ul>

            <div className="that_footer">
              <div className="total">
                合计:<span>￥</span>
                <span>{state?.totalCartAmount}</span>
              </div>
              <Button
                onClick={() => {
                  handleSubmit();
                }}
              >
                提交订单
              </Button>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default GoodsOrderPage;
